<?php

namespace app\astrteam\controller\v1;

use app\astrologer\controller\User;
use app\astrteam\model\Zlcr3ConsultTeam;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\ZlcrAstr;
use app\common\lib\Aes;
use app\common\lib\Alidayu;
use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use app\zyhsapi\service\CacheZyhs;
use think\Cache;
use think\Controller;
use think\Log;

class Login extends Controller
{
    /**
     * @throws \Exception
     */
    public function getCode()
    {
        $tel = trim(input('tel/s', ''));
        $time = input('time/d', 0);
        $sign = trim(input('sign/s', ''));
        // 手机号是否存在
        if (!preg_match("/^1[3456789]{1}\d{9}$/", $tel))
        {
            Log::write('手机号错误：' . $tel, 'error', true);
            throw new ApiException('手机号错误', 200, 0);
        }
        if (md5($tel . $time . 'd5kzqiT3DHn2XtYy') !== $sign)
        {
            Log::write('手机号验签错误：tel=' . $tel . ',time=' . $time . 'sign=' . $sign, 'error', true);
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $getCodeCheckCey = 'astr_team:getCode:' . $tel;
        if (CacheZyhs::get($getCodeCheckCey, false))
        {
            return show(config('code.error'), '手机号获取验证码太频繁，请稍后再试');
        }
        // 验证码是否过期
        $todayLoginGetCodeNumCheckKey = 'astr_team:login_code:' . date('Ymd') . ':get_num:' . $tel;
        $loginGetCodeNum = CacheZyhs::get($todayLoginGetCodeNumCheckKey, 0);
        if ($loginGetCodeNum >= 10)
        {
            return show(config('code.error'), '今日获取验证码次数过多，请明日再试');
        }
        if ($loginGetCodeNum === 0)
        {
            CacheZyhs::set($todayLoginGetCodeNumCheckKey, 1, 86400);
        } else
        {
            CacheZyhs::inc($todayLoginGetCodeNumCheckKey, 1);
        }

        $code = random_int(100000, 999999);// 六位验证码

        $alidayu = (new AppConfig())->configInfo('alidayu');

        $result = Alidayu::getInstance()->sendSmsZyhs($tel, $code, $alidayu['login_code'], 86, 'astr_team:login_code');

        if (!$result)
        {
            return show(config('code.error'), '发送失败');
        }
        $key_of_tel_code_login_error_num = 'login_error_zhunle_astrteam:' . $tel;
        CacheZyhs::rm($key_of_tel_code_login_error_num); // 登录

        CacheZyhs::set($getCodeCheckCey, 1, 55); // 获取验证码

        return show(config('code.success'), '发送成功');
    }

    /**
     * 手机号登录
     */
    public function mobile()
    {
        $tel = trim(input('tel/s', ''));
        $code = trim(input('code/s', ''));

        // 手机号是否存在
        if (!preg_match("/^1[3456789]{1}\d{9}$/", $tel))
        {
            Log::write('手机号错误：' . $tel, 'error', true);
            throw new ApiException('手机号错误', 200, 0);
        }

        // 短信验证码 或 密码是否存在
        if (empty($code))
        {
            return show(config('code.error'), '请输入验证码');
        }

        //防止暴力破解：手机号验证码登录失败10次后 除非重新获取验证码 否则验证码登录 验证码有效期（10分钟）内都自动错误
        $key_of_tel_code_login_error_num = 'login_error_zhunle_astrteam:' . $tel;
        if (CacheZyhs::get($key_of_tel_code_login_error_num, 0) >= 10)
        {
            Log::write($tel . '占星师团队 后台手机号验证码登录失败超过10次，验证码失效', 'error');
            return show(config('code.error'), '短信验证码错误！');
        }

        $appConfig = config('app');
        // 短信登录时，检测验证码是否正确
        if (!in_array($tel, $appConfig['mobile'], false) || (strpos($appConfig['code'] * (substr($tel, 3, 6)), $code) !== 0))
        {
            //  validate 严格校验
            $mobileCode = Alidayu::getInstance()->checkSmsIdentifyZyhs($tel, 86, 'astr_team:login_code'); // 获取验证码
            if ($code != $mobileCode)
            {// 如果验证码错误
                CacheZyhs::inc($key_of_tel_code_login_error_num);
                return show(config('code.error'), '短信验证码错误！');
            }
        }


        $zlcr3ConsultTeamModel = (new Zlcr3ConsultTeam());
        $astrTeamInfo = $zlcr3ConsultTeamModel->where(['contact_tel' => $tel])->field('id')->find();

        if ($astrTeamInfo)
        {
            try
            {
                // 生成token  和 token到期时间
                $token = IAuth::setAppLoginToken($tel);

                $data = [
                    'token' => $token,
                    'token_expire' => strtotime('+60 minute')
                ];

                $zlcr3ConsultTeamModel->SaveData($astrTeamInfo['id'], $data);
            }
            catch (\Exception $e)
            {
                Log::write($tel . '占星师团队    后台手机号验证码登录失败：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
                return show(config('code.error'), '登录失败，请稍后再试～');
            }

            $data = [
                'token' => (new Aes())->encryptWithOpenssl($token . '||' . $astrTeamInfo['id']),
            ];

            return show(config('code.success'), '登录成功', $data);
        }

        return show(440, '账户未注册！');
    }


}
